package cn.demoncat.util.web;

import cn.demoncat.util.exception.ConnRuntimeException;
import cn.demoncat.util.exception.ParamRuntimeException;
import cn.demoncat.util.web.constant.HttpConstant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 通过原生URL进行HTTP请求的工具
 * 
 * @author 延晓磊
 *
 * @since 2018年11月14日
 */
public final class HttpUrlUtil {

	/**
	 * GET请求
	 * 
	 * @param url	请求的URL，前缀http://
	 * @return
	 * 
	 * @author 延晓磊
	 *
	 * @since 2018年11月14日
	 */
	public static String doGet(String url) {
		URL uri;
		HttpURLConnection conn;
		StringBuilder result = new StringBuilder();
		String line;
		try {
			//创建URL
			uri = new URL(UrlUtil.trimHash(url));
		} catch (MalformedURLException e) {
			throw new ParamRuntimeException("URL格式错误：url = " + url, e);
		}
		try {
			//打开连接
			conn = (HttpURLConnection)uri.openConnection();
			conn.setConnectTimeout(60000);
			conn.setReadTimeout(60000);
			conn.setRequestMethod(HttpConstant.Method.GET);
			//读取响应
			if (conn.getResponseCode() == 200) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
				while ((line = reader.readLine()) != null) {
					 result.append(line);
				}
				return result.toString();
			}else {
				throw new ConnRuntimeException("URL连接失败：url = " + url + " , code = " + conn.getResponseCode());
			}
		} catch (IOException e) {
			throw new ConnRuntimeException("URL连接失败：url = " + url, e);
		}
	}
	
}
